package tn.bergaoui.openwebapp.wicket.pages;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.LoadableDetachableModel;

import tn.bergaoui.openwebapp.beans.BaseBean;
import tn.bergaoui.openwebapp.dao.GenericJpaDao;
import tn.bergaoui.openwebapp.wicket.components.ISubmitListener;
import tn.bergaoui.openwebapp.wicket.tools.EntityTools;

public abstract class BaseBeanEditorPanel<T extends BaseBean, TDao extends GenericJpaDao<T>> extends Panel {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected T bean;

	private ISubmitListener listener;

	public BaseBeanEditorPanel(String id, Long idplayer, ISubmitListener listener,
			final Component parent) {
		super(id);

		setOutputMarkupId(true);
		this.bean = getGenericDao().selectById(idplayer);
		this.listener = listener;

		add(new Label("title", EntityTools.getEntityLabel(bean)));

		Form form = new Form("personForm", new LoadableDetachableModel() {

			private static final long serialVersionUID = 1L;

			@Override
			protected Object load() {
				return BaseBeanEditorPanel.this.bean;
			}

		});

		AjaxButton abSave = new AjaxButton("savePlayer", form) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				T player = (T) form.getModelObject();

				getGenericDao().getEntityManager().getTransaction().begin();
				getGenericDao().save(player);
				getGenericDao().getEntityManager().getTransaction().commit();

				BaseBeanEditorPanel.this.listener.onSubmit();
				if (target != null) {
					target.addComponent(parent);
				}
			}
		};

	

		AjaxButton abCancel = new AjaxButton("cancelSavePlayer", form) {
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form form) {
				BaseBeanEditorPanel.this.listener.onCancel();
				if (target != null) {
					target.addComponent(parent);
				}
			}
		};

		addFormComponents(form);
		form.add(abSave);
		form.add(abCancel);
		
		add(form);
	}

	protected abstract void addFormComponents(Form form);

	public abstract TDao getGenericDao(); 

	




}
